import socket
from tqdm import *
import os
import binascii


def process_bar(percent, start_str='', end_str='', total_length=0):
    bar = ''.join(['|'] * int(percent * total_length)) + ''
    # bar = ''.join(["\033[31m%s\033[0m"%'   '] * int(percent * total_length)) + ''
    bar = '\r' + start_str + bar.ljust(total_length) + ' {:0>4.1f}%|'.format(percent*100) + end_str
    print(bar, end='', flush=True)


def main():
    c = 0
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.settimeout(30)
    client.connect(('192.168.4.1', 22333))
    file_leng = \
        os.path.getsize(r'C:\Users\Persai\Desktop\Engineering_training\machine_code\HAL_RTOS_gx\MDK-ARM\fireware.bin')
    with open(r'C:\Users\Persai\Desktop\Engineering_training\machine_code\HAL_RTOS_gx\MDK-ARM\fireware.bin', 'rb') as f:
        while True:
            process_bar(c / file_leng, start_str='', end_str='100%', total_length=15)
            file_data = f.read(32)
            s = str(binascii.b2a_hex(file_data))[2:-1]
            c += client.send(bytes().fromhex(s))
            n = client.recv(len(file_data))
            if n != file_data:
                print("error")
            if len(file_data) < 1:
                break
    print("\nfile size:")
    print(c)
    client.close()


if __name__ == "__main__":
    main()
